package com.yuhong.reggie.controller;

import com.yuhong.reggie.common.R;
import com.yuhong.reggie.entity.Employee;
import com.yuhong.reggie.entity.Page;
import com.yuhong.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
        @Autowired
        private EmployeeService employeeService;
        @PostMapping("/login")
        public R<Employee> login(@RequestBody Employee employee, HttpSession session){
            R<Employee> loginEmp = employeeService.login(employee);
            if (loginEmp.getCode()==1){
                session.setAttribute("employee", loginEmp.getData().getId());
            }
            return loginEmp;
        }
        @RequestMapping("/logout")
        public R<Integer> logout(HttpSession session){
            session.invalidate();
            return R.success(1);
        }

        //处理添加员工请求
    @RequestMapping
    public  R<String> save(@RequestBody Employee employee,HttpSession session){
        Long employeeId = (Long) session.getAttribute("employee");
        //完善数据
        employee.setCreateUser(employeeId);
        //修改人
        employee.setUpdateUser(employeeId);
        //调用业务
        employeeService.save(employee);
        return R.success("ok");
    }

    //分页请求
    @RequestMapping("/page")
    public R<Page<Employee>> findByName(Integer page,Integer pageSize,String name){
        Page<Employee> byPage = employeeService.findByPage(page, pageSize, name);
        return R.success(byPage);

    }

    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){
       //获取当前操作人的id
        Long employee1 = (Long) session.getAttribute("employee");

        //完善数据修改人
        employee.setUpdateUser(employee1);
        //调用业务修改
        employeeService.update(employee);
        //返回数据
        return R.success("ok");
    }
    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Integer id){
        R<Employee> employeeServiceById = employeeService.findById(id);

        return employeeServiceById;
    }
}




